﻿using ProtoBuf;
using System;
using System.IO;

namespace DCommon.Caching.Sample
{
    public class ProtobufSerializer : ICacheSerializer
    {
        public object Deserialize(byte[] data, Type type = null)
        {
            using (var stream = new MemoryStream(data))
            {
                if (type != null)
                    return Serializer.Deserialize(type, stream);
                else
                    return Serializer.Deserialize<object>(stream);
            }
        }

        public TItem Deserialize<TItem>(byte[] data)
        {
            using (var stream = new MemoryStream(data))
            {
                return Serializer.Deserialize<TItem>(stream);
            }
        }

        public byte[] Serialize<TItem>(TItem item)
        {
            using (var stream = new MemoryStream())
            {
                Serializer.Serialize(stream, item);
                return stream.ToArray();
            }
        }
    }
}
